package com.uatair.web.controller.business;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.uatair.common.core.domain.AjaxResult;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/module/hubeiData")
public class HubeiDataController {

    private final RestTemplate restTemplate;

    // 使用构造器注入（Spring 4.3+ 可以省略 @Autowired）
    public HubeiDataController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // 获取Token的接口
    private static final String TOKEN_URL = "https://agro.uatair.com/nyy/oauth2/client_token";
    // 获取湖北数据的接口
    private static final String DATA_URL = "https://agro.uatair.com/nyy/oauth2/taskInfo";

    @GetMapping("/getData")
    public AjaxResult getHubeiData() {
        try {
            // 1. 获取Token
            String token = getClientToken();
            if (token == null || token.isEmpty()) {
                return AjaxResult.error("获取Token失败");
            }

            // 2. 使用Token获取湖北数据
            ResponseEntity<String> dataResponse = getDataWithToken(token);
            if (dataResponse.getStatusCode() == HttpStatus.OK) {
                // 直接解析完整JSON响应
                JSONObject responseJson = JSON.parseObject(dataResponse.getBody());

                // 检查API是否返回成功
                if (responseJson.getInteger("code") == 200) {
                    // 返回完整的data对象
                    return AjaxResult.success("获取数据成功", responseJson.get("data"));
                }
                return AjaxResult.error("第三方API返回错误: " + responseJson.getString("msg"));
            }
            return AjaxResult.error("获取数据失败: " + dataResponse.getStatusCodeValue());
        } catch (Exception e) {
            return AjaxResult.error("系统异常: " + e.getMessage());
        }
    }
    private String getClientToken() {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            String requestUrl = UriComponentsBuilder.fromHttpUrl(TOKEN_URL)
                    .queryParam("client_id", "LFY")
                    .queryParam("client_secret", "k_54tdJWT.q2")
                    .queryParam("grant_type", "client_credentials")
                    .toUriString();

            HttpEntity<?> entity = new HttpEntity<>(headers);
            ResponseEntity<Map> response = restTemplate.exchange(
                    requestUrl,
                    HttpMethod.POST,
                    entity,
                    Map.class);

            // 关键修改：从 "client_token" 字段获取 Token
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return (String) response.getBody().get("client_token"); // 改为 client_token
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private ResponseEntity<String> getDataWithToken(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 直接在URL中拼接固定taskId
        String urlWithTaskId = DATA_URL + "?taskId=1939580129050669056";

        HttpEntity<?> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(
                urlWithTaskId,  // 使用带参数的URL
                HttpMethod.GET,
                entity,
                String.class);
    }
}